package com.chainyoung.common.base;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Message;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.webkit.DownloadListener;
import android.webkit.JavascriptInterface;
import android.webkit.RenderProcessGoneDetail;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebResourceRequest;
import android.webkit.WebResourceResponse;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.airbnb.lottie.LottieAnimationView;
import com.chainyoung.common.R;
import com.chainyoung.common.mvp.BasePresenter;
import com.chainyoung.common.utils.ToastUtil;
import com.chainyoung.router.RouterConstants;
import com.chainyoung.router.RouterUtils;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;

import butterknife.OnClick;

import static com.chainyoung.common.constant.CommonStringConstants.URL;

public abstract class OtherAppBaseActivity<P extends BasePresenter> extends BaseActivity<P> {


    protected WebView mWebView;
    protected LottieAnimationView mLottieAnimationView;
    protected ImageView ivBack;
    protected EditText editText;


    protected String url;

    protected String html;

    protected String address = "";

    private String TAG = getClass().getSimpleName();


    private ValueCallback<Uri> mUploadMessage;//回调图片选择，4.4以下
    private ValueCallback<Uri[]> mUploadCallbackAboveL;//回调图片选择，5.0以上
    private static final int FILE_SELECT_CODE = 0;

    protected String webTitle;


    String jsStr = "";
    String jsAppName="const appname=\"cbob\";";

    @Override
    protected void initUI() {
        mWebView = findViewById(R.id.webView);
        mLottieAnimationView = findViewById(R.id.LottieAnimationView);
        ivBack = findViewById(R.id.iv_left_image);
        editText = findViewById(R.id.title);

        url = getIntent().getStringExtra(URL);
        initSetting();

        try {
            InputStream in = mContext.getAssets().open("trust_min.js");
            byte buff[] = new byte[1024];
            ByteArrayOutputStream fromFile = new ByteArrayOutputStream();
            do {
                int numRead = in.read(buff);
                if (numRead <= 0) {
                    break;
                }
                fromFile.write(buff, 0, numRead);
            } while (true);
            jsStr = fromFile.toString();
            // jsStr=jsStr+"\n"+trasanctionJs;
            in.close();
            fromFile.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

        setListener();
        editText.clearFocus();

    }



    protected void setListener() {
        editText.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                    String url = editText.getText().toString().trim();
                    if (!url.isEmpty()) {
                        if (url.startsWith("http")) {
                            mWebView.loadUrl(url);
                        }
                    }
                    return false;
                }
                return false;
            }
        });

        ivBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
    }

    protected void setEditTitle(String title) {
        editText.setText(title);
        editText.setSelection(title.length());
    }


    @Override
    protected int getLayoutId() {
        return R.layout.activity_other_app_web_view;
    }


    @SuppressLint("NewApi")
    private void initSetting() {
        WebSettings webSettings = mWebView.getSettings();
        webSettings.setCacheMode(WebSettings.LOAD_NO_CACHE);
        if (Build.VERSION.SDK_INT >= 19) {
            webSettings.setLoadsImagesAutomatically(true);//图片自动缩放 打开
        } else {
            webSettings.setLoadsImagesAutomatically(false);//图片自动缩放 关闭
        }

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
            mWebView.setLayerType(View.LAYER_TYPE_SOFTWARE, null);//软件解码
        }
        mWebView.setLayerType(View.LAYER_TYPE_HARDWARE, null);//硬件解码

        webSettings.setJavaScriptEnabled(true); // 设置支持javascript脚本
//        webSettings.setPluginState(WebSettings.PluginState.ON);
        webSettings.setSupportZoom(true);// 设置可以支持缩放
        webSettings.setBuiltInZoomControls(true);// 设置出现缩放工具 是否使用WebView内置的缩放组件，由浮动在窗口上的缩放控制和手势缩放控制组成，默认false

        webSettings.setDisplayZoomControls(false);//隐藏缩放工具
        webSettings.setUseWideViewPort(true);// 扩大比例的缩放
        //mWebView.getSettings().setDefaultFontSize(40);
        webSettings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);//自适应屏幕
        webSettings.setLoadWithOverviewMode(true);

        webSettings.setSupportMultipleWindows(true);//支持多窗口

        webSettings.setAllowContentAccess(true);
        webSettings.setAllowFileAccessFromFileURLs(true);
        webSettings.setAllowUniversalAccessFromFileURLs(true);
        webSettings.setAllowFileAccess(true);

        webSettings.setDatabaseEnabled(true);//
        webSettings.setSavePassword(true);//保存密码
        webSettings.setDomStorageEnabled(true);//是否开启本地DOM存储  鉴于它的安全特性（任何人都能读取到它，尽管有相应的限制，将敏感数据存储在这里依然不是明智之举），Android 默认是关闭该功能的。
        mWebView.setSaveEnabled(true);
        mWebView.setKeepScreenOn(true);
        webSettings.setSupportMultipleWindows(true);

        // WebView.setWebContentsDebuggingEnabled(true);

        mWebView.setDownloadListener(new DownloadListener() {
            @Override
            public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimetype, long contentLength) {
                Uri uri = Uri.parse(url);
                Intent intent = new Intent(Intent.ACTION_VIEW, uri);
                startActivity(intent);
            }
        });

        mWebView.setWebViewClient(new WebViewClient());


        // 设置setWebChromeClient对象
        mWebView.setWebChromeClient(new WebChromeClient() {
            @Override
            public void onReceivedTitle(WebView view, String title) {
                super.onReceivedTitle(view, title);
                webTitle = title;

            }

            @Override
            public boolean onCreateWindow(WebView view, boolean isDialog, boolean isUserGesture, Message resultMsg) {
                return super.onCreateWindow(view, isDialog, isUserGesture, resultMsg);
//                WebView newWebView=new WebView(view.getContext());
//                newWebView.setWebViewClient(new WebViewClient(){
//                    @Override
//                    public boolean shouldOverrideUrlLoading(WebView view, String url) {
//                        mWebView.loadUrl(String.valueOf(url));
//                        return true;
//                    }
//               });
//                WebView.WebViewTransport transport = (WebView.WebViewTransport) resultMsg.obj;
//                transport.setWebView(newWebView);
//                resultMsg.sendToTarget();
//                return true;
            }

            @Override
            public void onProgressChanged(WebView view, int newProgress) {
                // TODO Auto-generated method stub
                mLottieAnimationView.setProgress(newProgress);
                super.onProgressChanged(view, newProgress);
                if (newProgress == 20) {
                    if (Build.VERSION.SDK_INT >= 19) {
                        mWebView.evaluateJavascript(jsStr, new ValueCallback<String>() {
                            @Override
                            public void onReceiveValue(String value) {//js与native交互的回调函数
                                Log.d("webview", "value=" + value);
                            }
                        });
                    }

                }
            }

            // For Android 3.0+
            public void openFileChooser(ValueCallback<Uri> uploadMsg) {

                mUploadMessage = uploadMsg;
                Intent i = new Intent(Intent.ACTION_GET_CONTENT);
                i.addCategory(Intent.CATEGORY_OPENABLE);
                i.setType("image/*");
                startActivityForResult(Intent.createChooser(i, "File Chooser"), FILE_SELECT_CODE);

            }

            // For Android 3.0+
            public void openFileChooser(ValueCallback uploadMsg, String acceptType) {
                mUploadMessage = uploadMsg;
                Intent i = new Intent(Intent.ACTION_GET_CONTENT);
                i.addCategory(Intent.CATEGORY_OPENABLE);
                i.setType("*/*");
                startActivityForResult(Intent.createChooser(i, "File Browser"), FILE_SELECT_CODE);
            }

            // For Android 4.1
            public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType, String capture) {
                mUploadMessage = uploadMsg;
                Intent i = new Intent(Intent.ACTION_GET_CONTENT);
                i.addCategory(Intent.CATEGORY_OPENABLE);
                i.setType("image/*");
                startActivityForResult(Intent.createChooser(i, "File Chooser"), FILE_SELECT_CODE);

            }

            // For Android 5.0+
            public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> filePathCallback, FileChooserParams fileChooserParams) {
                mUploadCallbackAboveL = filePathCallback;
                Intent i = new Intent(Intent.ACTION_GET_CONTENT);
                i.addCategory(Intent.CATEGORY_OPENABLE);
                i.setType("*/*");
                startActivityForResult(
                        Intent.createChooser(i, "File Browser"),
                        FILE_SELECT_CODE);
                return true;
            }


        });
        //设置此方法可在WebView中打开链接，反之用浏览器打开
        mWebView.setWebViewClient(new WebViewClient() {
            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
                if (!mWebView.getSettings().getLoadsImagesAutomatically()) {
                    mWebView.getSettings().setLoadsImagesAutomatically(true);
                }
                mLottieAnimationView.setVisibility(View.GONE);
                // mWebView.loadUrl("javascript:" + jsStr);
//                if (Build.VERSION.SDK_INT >= 19) {
//                    mWebView.evaluateJavascript(jsStr, new ValueCallback<String>() {
//                        @Override public void onReceiveValue(String value) {//js与native交互的回调函数
//                            Log.d("webview", "value=" + value);
//                        }
//                    });
//                }
                view.loadUrl("javascript: var allLinks = document.getElementsByTagName('a'); if (allLinks) {var i;for (i=0; i<allLinks.length; i++) {var link = allLinks[i];var target = link.getAttribute('target'); if (target && target == '_blank') {link.href = 'newtab:'+link.href;link.setAttribute('target','_self');}}}");

            }


            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {

                mLottieAnimationView.setVisibility(View.VISIBLE);

                super.onPageStarted(view, url, favicon);
                if (Build.VERSION.SDK_INT >= 19) {
                    mWebView.evaluateJavascript(jsAppName, new ValueCallback<String>() {
                        @Override
                        public void onReceiveValue(String value) {//js与native交互的回调函数
                            Log.d("webview", "value=" + value);
                        }
                    });

                }


            }


            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                if (url.startsWith("newtab:")) {
                    view.loadUrl(url.replace("newtab:", ""));
                    return false;
                } else if ((url.startsWith("http:") || url.startsWith("https:"))) {
                    view.loadUrl(url);
                    return false;
                }
                return true;

//                if (url.equals(ServerConstant.BMGAME_DOWNLOAD)) {
//                    if (AppUtils.isInstallApp(mContext, PkgName.BM_GAME.pkgName)) {
//                        Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(ServerConstant.BM_URI));
//                        startActivity(intent);
//                    }
//                }

            }


            @Nullable
            @Override
            public WebResourceResponse shouldInterceptRequest(WebView view, WebResourceRequest request) {

                Log.d(TAG, request.getUrl().toString());
                return super.shouldInterceptRequest(view, request);

//                if (request.getUrl().startsWith("http") || url.startsWith("https")) {
//                    return super.shouldInterceptRequest(view, url);
//                } else {
//                    Intent in = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
//                    startActivity(in);
//                    return null;
//                }
            }

            @Nullable
            @Override
            public WebResourceResponse shouldInterceptRequest(WebView view, String url) {
                return super.shouldInterceptRequest(view, url);
            }
        });


        if (!TextUtils.isEmpty(url)) {
            mWebView.loadUrl(url);
        }

        mWebView.addJavascriptInterface(new JavaScriptinterface(this),
                "android");


    }


    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        Log.i(TAG, "onKeyDown: keyCode -- " + keyCode);
        if (event.getAction() == KeyEvent.ACTION_DOWN) {
            if (keyCode == KeyEvent.KEYCODE_BACK && mWebView.canGoBack()) {  //表示按返回键

//                        时的操作
                mWebView.loadUrl("javascript:executeCallback(8888,\"canceled\",null)");
                mWebView.goBack();   //后退
                return true;    //已处理
            } else {
                finish();
                return true;
            }
        }
        return super.onKeyDown(keyCode, event);

    }

    class JavaScriptinterface {
        Context context;

        public JavaScriptinterface(Context c) {
            context = c;
        }

        /**
         * 与js交互时用到的方法，在js里直接调用的
         */
        @JavascriptInterface
        public void onFinish() {
            finish();
        }

        @JavascriptInterface
        public void signTransaction(String transactionInfo) {
            getWebTransactionInfo(transactionInfo);
        }

        @JavascriptInterface
        public void signMessage(Object data) {
            ToastUtil.showToast(data.toString());
        }

        @JavascriptInterface
        public void signPersonalMessage(Object data) {
            ToastUtil.showToast(data.toString());
        }

        @JavascriptInterface
        public void signTypedMessage(Object data) {
            ToastUtil.showToast(data.toString());
        }

        @JavascriptInterface
        public String setAddr() {
            return address;
        }


    }


    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode != Activity.RESULT_OK) {
            if (Build.VERSION.SDK_INT >= 21) {//5.0以上版本处理
                mUploadCallbackAboveL.onReceiveValue(null);//回调给js
            } else {
                //4.4以下处理
                mUploadMessage.onReceiveValue(null);
            }
            return;
        }

        switch (requestCode) {
            case FILE_SELECT_CODE: {
                if (Build.VERSION.SDK_INT >= 21) {//5.0以上版本处理
                    Uri uri = data.getData();
                    Uri[] uris = new Uri[]{uri};
                   /* ClipData clipData = data.getClipData();  //选择多张
                    if (clipData != null) {
                        for (int i = 0; i < clipData.getItemCount(); i++) {
                            ClipData.Item item = clipData.getItemAt(i);
                            Uri uri = item.getUri();
                            uris[i]=uri;
                        }
                    }*/
                    mUploadCallbackAboveL.onReceiveValue(uris);//回调给js
                } else {//4.4以下处理
                    Uri uri = data.getData();
                    mUploadMessage.onReceiveValue(uri);
                }


            }
            break;
        }
    }

    /**
     * 获取到Dapp 交易数据
     *
     * @param transactionInfo
     */
    protected void getWebTransactionInfo(String transactionInfo) {


    }


    @Override
    protected void onResume() {
        super.onResume();
        // mWebView.onResume();
        // mWebView.pauseTimers();

    }

    @Override
    protected void onPause() {
        super.onPause();
        // mWebView.onPause();
        // mWebView.resumeTimers();
    }
}
